package exer;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Enumeration;

/**
 * @author tongchen
 * @create 2023-04-01 15:36
 * 测试请求中的各种方法
 */
//设置注解，使浏览器可以访问
    @WebServlet("/showRequest")
public class ShowRequest extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //在涉及前后端交互的过程中，最先要确定的就是在数据传输过程中的编码格式问题
        //确定传输过来数据的编码格式
        req.setCharacterEncoding("utf-8");
        //确定返回响应的编码格式
        resp.setContentType("text/html;charset=utf-8");
        //创建StringBuilder
        StringBuilder stringBuilder = new StringBuilder();
        //获取请求方法
        String method = req.getMethod();
        stringBuilder.append(method);
        //换行
        stringBuilder.append("<br>");
        //获取URL
        String requestURI = req.getRequestURI();
        stringBuilder.append(requestURI);
        stringBuilder.append("<br>");
        //获取协议和版本号
        String protocol = req.getProtocol();
        stringBuilder.append(protocol);
        stringBuilder.append("<br>");
        //获取跟路径
        String contextPath = req.getContextPath();
        stringBuilder.append(contextPath);
        stringBuilder.append("<br>");
        //获取queryString
        String queryString = req.getQueryString();
        stringBuilder.append(queryString);
        stringBuilder.append("<br>");
        stringBuilder.append("++++++++++++++++++++");
        //获取请求报头信息
        Enumeration<String> headerNames = req.getHeaderNames();
        while(headerNames.hasMoreElements()){
            String elementKey = headerNames.nextElement();
            String elementValue = req.getHeader(elementKey);
            stringBuilder.append(elementKey+" "+ elementValue);
            stringBuilder.append("<br>");


        }
        //将全部信息写回浏览器
        resp.getWriter().write(stringBuilder.toString());

    }
}
